# -*- coding:utf-8 -*-
from __future__ import division
from dao.MySqlDAL import MySqlDAL
from collections import defaultdict
import json
from util.stock_utils import stocks_id
import numpy as np
# from collections import Counter
__author__ = 'shudongma.msd(风骐)'

sqlUtil = MySqlDAL()

# type '最热：0   最赚钱：收益高 111 月 ，涨跌快 112 月 ， 收益高 121 日 ， 涨跌快 122 日   最人气：2
def getCubeWeight(strdate):
    res = sqlUtil.get_dimensions_rows("SELECT symbol,type,rank_num,date FROM tb_cube_rank WHERE date='"+strdate+"' and rank_num<=100")
    '''
    weight_dict = {'symbol':{'$type':weight}}
    '''
    cube_weight = defaultdict(dict)
    for row in res:
        cube_weight[row['symbol']][str(row['type'])] = (101-row['rank_num'])/100
    return cube_weight

def getStockInfoOfCube(strdate):
    cube_weight = getCubeWeight(strdate)
    res = sqlUtil.get_dimensions_rows("SELECT symbol,date,daily_gain,monthly_gain,total_gain,"
                                      "net_value,follower_count,style,tag,stock_group FROM tb_cube_info WHERE date='"+strdate+"'")
    '''
        stock_weight = {stock_id:{'type':{'weight':'占比','day_gain':'','mon_gain':'','tot_gain':''
        ,'follower':'','style':''}}}
    '''
    stock_weight = defaultdict(dict)
    for row in res:
        if row['symbol'] not in cube_weight.keys():
            continue
        # 处理 组合投资风格
        row['style'] = row['style'].strip()
        if row['style'] == u'疯狂过山车':
            row['style'] = 2
        elif row['style'] == u'上蹿下跳':
            row['style'] = 4
        elif row['style'] == u'小浪花':
            row['style'] = 8
        elif row['style'] == u'稳如泰山':
            row['style'] = 16

        tmpl = json.loads(row['stock_group'])
        if tmpl == 0:
            continue
        for vl in tmpl:
            for k,v in cube_weight[row['symbol']].iteritems():
                if k not in stock_weight[vl[0]]:
                    stock_weight[vl[0]][k] = dict()
                    stock_weight[vl[0]][k]['style'] = list()
                stock_weight[vl[0]][k]['weight'] = stock_weight[vl[0]][k].get('weight',0) + v*float(vl[1])/100

                # stock_weight[vl[0]][k]['day_gain'] = stock_weight[vl[0]][k].get('day_gain',0) + v*row['daily_gain']
                # stock_weight[vl[0]][k]['mon_gain'] = stock_weight[vl[0]][k].get('mon_gain',0) + v*row['monthly_gain']
                # stock_weight[vl[0]][k]['tot_gain'] = stock_weight[vl[0]][k].get('tot_gain',0) + v*row['total_gain']
                stock_weight[vl[0]][k]['follower'] = stock_weight[vl[0]][k].get('follower',0) + v*row['follower_count']
                stock_weight[vl[0]][k]['day_gain'] = stock_weight[vl[0]][k].get('day_gain',0) + v*row['daily_gain']*float(vl[1])/100
                stock_weight[vl[0]][k]['mon_gain'] = stock_weight[vl[0]][k].get('mon_gain',0) + v*row['monthly_gain']*float(vl[1])/100
                stock_weight[vl[0]][k]['tot_gain'] = stock_weight[vl[0]][k].get('tot_gain',0) + v*row['total_gain']*float(vl[1])/100
                # stock_weight[vl[0]][k]['follower'] = stock_weight[vl[0]][k].get('follower',0) + v*row['follower_count']*float(vl[1])/100

                stock_weight[vl[0]][k]['style'].append(row['style'])

    # 为缺少的数据配置默认值
    # type':{'weight':[],'day_gain':[],'mon_gain':[],'tot_gain':[],'follower':[],'style':[]}
    dv_dict = defaultdict(dict)
    for vd in stock_weight.values():
        for k,v in vd.iteritems():
            if k not in dv_dict:
                dv_dict[k]['weight'] = list()
                dv_dict[k]['day_gain'] = list()
                dv_dict[k]['mon_gain'] = list()
                dv_dict[k]['tot_gain'] = list()
                dv_dict[k]['follower'] = list()
                dv_dict[k]['style'] = list()
            dv_dict[k]['weight'].append(v['weight'])
            dv_dict[k]['day_gain'].append(v['day_gain'])
            dv_dict[k]['mon_gain'].append(v['mon_gain'])
            dv_dict[k]['tot_gain'].append(v['tot_gain'])
            dv_dict[k]['follower'].append(v['follower'])
            v['style'] = sum(set(v['style']))
            dv_dict[k]['style'].append(v['style'])
    # 对缺失组合的股票默认值进行处理
    for k,v in dv_dict.iteritems():
        dv_dict[k]['weight'] = min(v['weight'])/2
        dv_dict[k]['day_gain'] = np.mean(v['day_gain'])
        dv_dict[k]['mon_gain'] = np.mean(v['mon_gain'])
        dv_dict[k]['tot_gain'] = np.mean(v['tot_gain'])
        dv_dict[k]['follower'] = min(v['follower'])/2
        # tc = Counter(v['style'])
        # dv_dict[k]['style'] = tc.most_common(1)[0][0]
        dv_dict[k]['style'] = 0 # 0代表没有组合包含它
    for item in stocks_id:
        if item not in stock_weight:
            for k,v in dv_dict.iteritems():
                stock_weight[item][k] = dict()
                stock_weight[item][k]['weight'] = v['weight']
                stock_weight[item][k]['day_gain'] = v['day_gain']
                stock_weight[item][k]['mon_gain'] = v['mon_gain']
                stock_weight[item][k]['tot_gain'] = v['tot_gain']
                stock_weight[item][k]['follower'] = v['follower']
                stock_weight[item][k]['style'] = v['style']
        else:
            for k,v in dv_dict.iteritems():
                if k not in stock_weight[item]:
                    stock_weight[item][k] = dict()
                    stock_weight[item][k]['weight'] = v['weight']
                    stock_weight[item][k]['day_gain'] = v['day_gain']
                    stock_weight[item][k]['mon_gain'] = v['mon_gain']
                    stock_weight[item][k]['tot_gain'] = v['tot_gain']
                    stock_weight[item][k]['follower'] = v['follower']
                    stock_weight[item][k]['style'] = v['style']

    return stock_weight


#
# def getStockInfoOfCube(strdate):
#     cube_weight = getCubeWeight(strdate)
#     res = sqlUtil.get_dimensions_rows("SELECT symbol,date,daily_gain,monthly_gain,total_gain,"
#                                       "net_value,follower_count,style,tag,stock_group FROM tb_cube_info WHERE date='"+strdate+"'")
#     '''
#         stock_weight = {stock_id:{'type':{'weight':'占比','day_gain':'','mon_gain':'','tot_gain':''
#         ,'follower':'','style':''}}}
#     '''
#     stock_weight = defaultdict(dict)
#     for row in res:
#         if row['symbol'] not in cube_weight.keys():
#             continue
#         # 处理 组合投资风格
#         row['style'] = row['style'].strip()
#         if row['style'] == u'疯狂过山车':
#             row['style'] = 2
#         elif row['style'] == u'上蹿下跳':
#             row['style'] = 4
#         elif row['style'] == u'小浪花':
#             row['style'] = 8
#         elif row['style'] == u'稳如泰山':
#             row['style'] = 16
#
#         tmpl = json.loads(row['stock_group'])
#         if tmpl == 0:
#             continue
#         for vl in tmpl:
#             for k,v in cube_weight[row['symbol']].iteritems():
#                 if k not in stock_weight[vl[0]]:
#                     stock_weight[vl[0]][k] = dict()
#                     stock_weight[vl[0]][k]['style'] = list()
#                 stock_weight[vl[0]][k]['weight'] = stock_weight[vl[0]][k].get('weight',0) + v*float(vl[1])/100
#                 stock_weight[vl[0]][k]['follower'] = stock_weight[vl[0]][k].get('follower',0) + v*row['follower_count']
#                 stock_weight[vl[0]][k]['day_gain'] = stock_weight[vl[0]][k].get('day_gain',0) + v*row['daily_gain']*float(vl[1])/100
#                 stock_weight[vl[0]][k]['mon_gain'] = stock_weight[vl[0]][k].get('mon_gain',0) + v*row['monthly_gain']*float(vl[1])/100
#                 stock_weight[vl[0]][k]['tot_gain'] = stock_weight[vl[0]][k].get('tot_gain',0) + v*row['total_gain']*float(vl[1])/100
#
#                 stock_weight[vl[0]][k]['style'].append(row['style'])
#
#     # 为缺少的数据配置默认值
#     # type':{'weight':[],'day_gain':[],'mon_gain':[],'tot_gain':[],'follower':[],'style':[]}
#     dv_dict = defaultdict(dict)
#     for vd in stock_weight.values():
#         for k,v in vd.iteritems():
#             if k not in dv_dict:
#                 dv_dict[k]['weight'] = list()
#                 dv_dict[k]['day_gain'] = list()
#                 dv_dict[k]['mon_gain'] = list()
#                 dv_dict[k]['tot_gain'] = list()
#                 dv_dict[k]['follower'] = list()
#                 dv_dict[k]['style'] = list()
#             dv_dict[k]['weight'].append(v['weight'])
#             dv_dict[k]['day_gain'].append(v['day_gain'])
#             dv_dict[k]['mon_gain'].append(v['mon_gain'])
#             dv_dict[k]['tot_gain'].append(v['tot_gain'])
#             dv_dict[k]['follower'].append(v['follower'])
#             v['style'] = sum(set(v['style']))
#             dv_dict[k]['style'].append(v['style'])
#     # 对缺失组合的股票默认值进行处理
#     for k,v in dv_dict.iteritems():
#         dv_dict[k]['weight'] = [max(v['weight']),min(v['weight']),np.mean(v['weight']),np.std(v['weight'])]
#         dv_dict[k]['day_gain'] = [max(v['day_gain']),min(v['day_gain']),np.mean(v['day_gain']),np.std(v['day_gain'])]
#         dv_dict[k]['mon_gain'] = [max(v['mon_gain']),min(v['mon_gain']),np.mean(v['mon_gain']),np.std(v['mon_gain'])]
#         dv_dict[k]['tot_gain'] = [max(v['tot_gain']),min(v['tot_gain']),np.mean(v['tot_gain']),np.std(v['tot_gain'])]
#         dv_dict[k]['follower'] = [max(v['follower']),min(v['follower']),np.mean(v['follower']),np.std(v['follower'])]
#         dv_dict[k]['style'] = [max(v['style']),min(v['style']),np.mean(v['style']),np.std(v['style'])]
#     for item in stocks_id:
#         if item not in stock_weight:
#             for k,v in dv_dict.iteritems():
#                 stock_weight[item][k] = dict()
#                 stock_weight[item][k]['weight'] = 0
#                 stock_weight[item][k]['day_gain'] = 0
#                 stock_weight[item][k]['mon_gain'] = 0
#                 stock_weight[item][k]['tot_gain'] = 0
#                 stock_weight[item][k]['follower'] = 0
#                 stock_weight[item][k]['style'] = 0
#         else:
#             for k,v in dv_dict.iteritems():
#                 if k not in stock_weight[item]:
#                     stock_weight[item][k] = dict()
#                     stock_weight[item][k]['weight'] = 0
#                     stock_weight[item][k]['day_gain'] = 0
#                     stock_weight[item][k]['mon_gain'] = 0
#                     stock_weight[item][k]['tot_gain'] = 0
#                     stock_weight[item][k]['follower'] = 0
#                     stock_weight[item][k]['style'] = 0
#                 else:
#                     stock_weight[item][k]['weight'] = (stock_weight[item][k]['weight']-v['weight'][2])/v['weight'][3]
#                     stock_weight[item][k]['day_gain'] = (stock_weight[item][k]['day_gain']-v['day_gain'][2])/v['day_gain'][3]
#                     stock_weight[item][k]['mon_gain'] = (stock_weight[item][k]['mon_gain']-v['mon_gain'][2])/v['mon_gain'][3]
#                     stock_weight[item][k]['tot_gain'] = (stock_weight[item][k]['tot_gain']-v['tot_gain'][2])/v['tot_gain'][3]
#                     stock_weight[item][k]['follower'] = (stock_weight[item][k]['follower']-v['follower'][2])/v['follower'][3]
#                     # stock_weight[item][k]['style'] = 0
#     return stock_weight

# print getStockInfoOfCube('2016-03-14')
